#!/bin/bash

############################################################################
#
# 在终端（粘贴）执行如下命令，可远程执行该脚本：
#
#   curl -sSL https://gitee.com/tay3223/biubiubiu/raw/master/script-prometheus/centos7-install-blackbox_exporter.sh | /bin/bash
#
############################################################################

function install_exporter() {
    mkdir -p /opt/monitoring
    wget https://osoc.oss-cn-shanghai.aliyuncs.com/bao/prometheus/prometheus-2.27.1/blackbox_exporter-0.19.0.linux-amd64/blackbox_exporter -O /opt/monitoring/blackbox_exporter
    wget https://osoc.oss-cn-shanghai.aliyuncs.com/bao/prometheus/prometheus-2.27.1/blackbox_exporter-0.19.0.linux-amd64/blackbox.yml -O /opt/monitoring/blackbox.yml
    chmod +x /opt/monitoring/blackbox_exporter
    /opt/monitoring/blackbox_exporter --version
}

function register_daemons() {
    local SERVICE_PATH="/usr/lib/systemd/system/blackbox_exporter.service"
    cat <<EOF >${SERVICE_PATH}
[Unit]
Description=blackbox_exporter
After=network.target


[Service]
Type=simple
User=root
Group=root
LimitNOFILE=100000
LimitNPROC=100000
ExecStart=/opt/monitoring/blackbox_exporter --web.listen-address=:9115 --config.file=/opt/monitoring/blackbox.yml
Restart=no


[Install]
WantedBy=multi-user.target
EOF

    chmod 644 ${SERVICE_PATH}
    systemctl daemon-reload
    systemctl enable blackbox_exporter.service
}

function help() {
    cat <<EOF
===================================

[√]  1.blackbox_exporter 守护进程已注册
[√]  2.blackbox_exporter 开机启动已完成
[√]  3.blackbox_exporter 运行端口为：9115


#重新加载systemctl服务器
systemctl daemon-reload

#常用命令
systemctl start   blackbox_exporter.service
systemctl status  blackbox_exporter.service
systemctl stop    blackbox_exporter.service
systemctl restart blackbox_exporter.service
systemctl enable  blackbox_exporter.service

===================================
EOF
}

#关闭已有的守护进程
if (systemctl stop blackbox_exporter.service); then
    echo -e "\n守护进程关闭成功\n"
else
    echo -e "\n守护进程不存在，无需关闭\n"
fi

#函数调用
install_exporter
register_daemons
help
